<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>发票基本信息</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买方名称" prop="buyerName">
              <el-input v-model="form.buyerName" placeholder="请输入购买方名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售方名称" prop="sellerName">
              <el-input v-model="form.sellerName" placeholder="请输入销售方名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价税合计" prop="totalAmount">
              <el-input v-model="form.totalAmount" placeholder="请输入价税合计" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税额" prop="taxAmount">
              <el-input v-model="form.taxAmount" placeholder="请输入税额" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>商品明细</span>
        </div>
        <el-table :data="form.invoiceItems" :row-class-name="tableRowClassName">
          <el-table-column label="商品名称" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsName" placeholder="请输入商品名称" />
            </template>
          </el-table-column>
          <el-table-column label="数量" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入数量" type="number" />
            </template>
          </el-table-column>
          <el-table-column label="单价" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unitPrice" placeholder="请输入单价" type="number" />
            </template>
          </el-table-column>
          <el-table-column label="金额" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.amount" placeholder="请输入金额" type="number" />
            </template>
          </el-table-column>
          <el-table-column label="税率" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.taxRate" placeholder="请输入税率" type="number" />
            </template>
          </el-table-column>
          <el-table-column label="税额" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.taxAmount" placeholder="请输入税额" type="number" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handleDeleteItem(scope.$index)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px;">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddItem">添加商品</el-button>
        </div>
      </el-card>

      <el-card class="box-card" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>操作区</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="24">
            <div style="text-align: center;">
              <el-button type="primary" @click="handlePreview">预览</el-button>
              <el-button type="success" @click="handleIssueInvoice">开具发票</el-button>
              <el-button type="warning" :disabled="!downloadEnabled" @click="handleDownload">下载发票</el-button>
              <el-button @click="handleCancel">返回</el-button>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <!-- 发票预览对话框 -->
    <el-dialog :title="previewTitle" :visible.sync="previewOpen" width="800px" append-to-body>
      <div v-if="previewData" class="preview-content">
        <h2 style="text-align: center;">增值税发票预览</h2>
        <p><strong>发票代码：</strong>{{ previewData.invoiceCode }}</p>
        <p><strong>发票号码：</strong>{{ previewData.invoiceNumber }}</p>
        <p><strong>购买方名称：</strong>{{ previewData.buyerName }}</p>
        <p><strong>销售方名称：</strong>{{ previewData.sellerName }}</p>
        <p><strong>价税合计：</strong>{{ previewData.totalAmount }}</p>
        <p><strong>税额：</strong>{{ previewData.taxAmount }}</p>
        <p><strong>备注：</strong>{{ previewData.remark }}</p>
        <!-- 这里可以添加更详细的预览内容 -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPendingInvoiceDetails, previewInvoice, issueInvoice, downloadInvoice } from "@/api/fiscale/tax";

export default {
  name: "InvoiceIssue",
  data() {
    return {
      // 表单参数
      form: {
        buyerName: null,
        sellerName: null,
        totalAmount: null,
        taxAmount: 0,
        remark: null,
        invoiceItems: [{
          goodsName: null,
          quantity: null,
          unitPrice: null,
          amount: null,
          taxRate: null,
          taxAmount: null
        }]
      },
      // 表单校验
      rules: {
        buyerName: [{ required: true, message: "购买方名称不能为空", trigger: "blur" }],
        sellerName: [{ required: true, message: "销售方名称不能为空", trigger: "blur" }],
        totalAmount: [{ required: true, message: "价税合计不能为空", trigger: "blur" }]
      },
      // 预览对话框
      previewOpen: false,
      previewTitle: "发票预览",
      previewData: null,
      // 下载按钮是否启用
      downloadEnabled: false,
      // 发票ID
      invoiceId: null
    };
  },
  created() {
    const declarationIds = this.$route.query.declarationIds;
    if (declarationIds) {
      this.loadPendingInvoiceDetails(declarationIds.split(',').map(id => parseInt(id)));
    }
  },
  methods: {
    /** 加载待开票详情 */
    loadPendingInvoiceDetails(declarationIds) {
      getPendingInvoiceDetails(declarationIds).then(response => {
        // 预填充数据
        if (response.data && response.data.length > 0) {
          // 使用第一个报关单的数据作为默认值
          const firstDeclaration = response.data[0];
          this.form.buyerName = firstDeclaration.consigneeName || "境外收货人"; // 假设有收货人字段
          this.form.sellerName = "企业自身"; // 企业自身信息
          this.form.totalAmount = firstDeclaration.totalAmount;
          this.form.taxAmount = 0; // 税额为0
          this.form.remark = "对应报关单号：" + firstDeclaration.declarationNo;
          
          // 预填充商品明细
          this.form.invoiceItems = [];
          if (firstDeclaration.declarationItemList && firstDeclaration.declarationItemList.length > 0) {
            firstDeclaration.declarationItemList.forEach(item => {
              this.form.invoiceItems.push({
                goodsName: item.goodsName,
                quantity: item.quantity,
                unitPrice: item.unitPrice,
                amount: item.amount,
                taxRate: 0,
                taxAmount: 0
              });
            });
          } else {
            // 如果没有商品明细，添加一个空行
            this.form.invoiceItems.push({
              goodsName: null,
              quantity: null,
              unitPrice: null,
              amount: null,
              taxRate: null,
              taxAmount: null
            });
          }
        }
      });
    },
    /** 添加商品 */
    handleAddItem() {
      this.form.invoiceItems.push({
        goodsName: null,
        quantity: null,
        unitPrice: null,
        amount: null,
        taxRate: null,
        taxAmount: null
      });
    },
    /** 删除商品 */
    handleDeleteItem(index) {
      if (this.form.invoiceItems.length === 1) {
        this.$message.warning("至少保留一条商品明细");
        return;
      }
      this.form.invoiceItems.splice(index, 1);
    },
    /** 表格行样式 */
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    /** 预览 */
    handlePreview() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          previewInvoice(this.form).then(response => {
            this.previewData = response.data;
            this.previewOpen = true;
          });
        }
      });
    },
    /** 开具发票 */
    handleIssueInvoice() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取报关单ID
          const declarationIds = this.$route.query.declarationIds;
          if (declarationIds) {
            this.form.declarationIds = declarationIds.split(',').map(id => parseInt(id));
          }
          
          issueInvoice(this.form).then(response => {
            this.$modal.msgSuccess("开票成功");
            this.invoiceId = response.data.invoiceId;
            this.downloadEnabled = true;
          }).catch(error => {
            this.$modal.msgError("开票失败：" + error.message);
          });
        }
      });
    },
    /** 下载发票 */
    handleDownload() {
      if (this.invoiceId) {
        downloadInvoice(this.invoiceId).then(response => {
          // 实际实现中应该下载PDF文件
          this.$modal.msgSuccess("发票下载链接已生成，请点击下载");
        });
      }
    },
    /** 取消按钮 */
    handleCancel() {
      this.$router.go(-1);
    }
  }
};
</script>

<style scoped>
.preview-content {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
</style>